package com.company.linkedList;

public class MergeInBetween {
    public ListNode mergeInBetween(ListNode list1, int a, int b, ListNode list2) {
        if (list1 ==null) {
            return null;
        }
        ListNode nodeB = getNodeByIndex(list1, b);

        ListNode preNodeA = getNodeByIndex(list1,a-1);
        ListNode nextNodeB = getNodeByIndex(list1,b+1);

        preNodeA.next = null;
        nodeB.next = null;

        if (list2 ==null) {
            preNodeA.next = nextNodeB;
        }else {
            preNodeA.next = list2;
            getListTail(list2).next = nextNodeB;
        }
        return list1;

    }

    private ListNode getListTail(ListNode head) {
        ListNode node = head;
        while (node.next != null) {
            node = node.next;
        }
        return node;
    }

    private ListNode findNodeByValue(ListNode head, int v) {
        ListNode node = head;
        while (node != null) {
            if (node.val == v) {
                return node;
            }
            node = node.next;
        }
        return null;
    }

    private int getNodeIndexByValue(ListNode head, int v) {
        int index = -1;
        ListNode node = head;
        while (node != null) {
            index++;
            if (node.val == v) {
                break;
            }
            node = node.next;
        }
        return index;
    }

    private ListNode getNodeByIndex(ListNode head, int index) {
        ListNode node = head;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

}
